<template>
	<view class="box">
		<view id="top">
			<!-- 轮播 -->
			<view class="swiper">
				<u-swiper
					:list="bannerList"
					keyName="image"
					showTitle
					indicator
					indicatorMode="line"
					circular
					indicatorStyle="left:40rpx"
					height="526rpx"
					:radius="0"
					@click="swiperClick"
				></u-swiper>
			</view>

			<!-- 发布按钮 -->
			<uni-transition mode-class="fade" :show="ifNavBarChange">
				<view class="publish-icon" @click="toRelease"><u-icon name="plus" color="#FFFFFF" size="24"></u-icon></view>
			</uni-transition>
			<!-- 导航 -->
			<view class="navbar" id="nav">
				<u-navbar :safeAreaInsetTop="true" leftIcon="" :bgColor="ifNavBarChange ? '#FFF' : 'transparent'" :placeholder="true">
					<view class="navbar-left" :style="{ color: ifNavBarChange ? '#000' : '#FFFFFF' }" slot="left">社区</view>

					<view slot="center"></view>

					<view class="navbar-right flex-no-horizontal" slot="right">
						<!-- <view class="navbar-right-icon" style="margin-right: 20rpx;" @click="toSearch">
							<u-icon name="search" color="#FFFFFF" size="35"></u-icon>
						</view> -->

						<view class="navbar-right-icon" style="margin-right: 20rpx;" @click="toRelease" v-show="!ifNavBarChange">
							<u-icon name="plus" :color="ifNavBarChange ? '#000' : '#FFFFFF'" size="25"></u-icon>
						</view>

						<view class="navbar-right-icon" style="position: relative;" @click="toMessage">
							<u-badge
								style="z-index: 1;"
								numberType="overflow"
								max="99"
								:value="message.commentNum + message.followers + message.likeNum"
								:absolute="true"
								:offset="[-2, -6]"
							></u-badge>
							<u--image src="../../static/xiaoxi.png" width="48rpx" height="48rpx" v-show="ifNavBarChange"></u--image>
							<u--image src="../../static/img/news-white.png" width="48rpx" height="48rpx" v-show="!ifNavBarChange"></u--image>
						</view>
					</view>
				</u-navbar>
			</view>
			<view class="box-pading">
				<!-- 四个icon -->
				<view class="main flex-no-horizontal">
					<view class="main-item" v-for="(item, index) in kingkongList" :key="item.id" @click="kingkongClick(item)">
						<image :src="item.image" mode=""></image>
						<view>{{ item.title }}</view>
					</view>
				</view>
			</view>
		</view>
		<u-sticky :offset-top="offsetTop" v-if="offsetTop !== 0 && isShowTabs" class="box-pading">
			<view class="tabs" id="tabs">
				<u-tabs
					:list="tabsList"
					@click="tabsClick"
					:current="tabActiveIndex"
					:activeStyle="{ color: '#000000', fontWeight: 'bold', fontSize: '18px' }"
					:inactiveStyle="{ color: 'rgba(143, 144, 145, 1)', fontSize: '15px' }"
					:lineColor="'#19be6b'"
				></u-tabs>
			</view>
		</u-sticky>
		<view class="box-pading">
			<z-paging
				ref="paging"
				v-model="dataList"
				@query="queryList"
				:empty-view-img="empty.emptyImgUrl"
				:auto-clean-list-when-reload="false"
				:refresher-end-bounce-enabled="false"
				:auto-scroll-to-top-when-reload="false"
				:auto-show-back-to-top="true"
				back-to-top-bottom="140rpx"
				back-to-top-threshold="200px"
				:empty-view-img-style="empty.emptyImgStyle"
				:empty-view-text="empty.emptyText"
				:use-page-scroll="true"
			>
				<!-- 动态 -->
				<dynamic
					v-for="item in dataList"
					:key="item.dynamicId"
					:record="item"
					:ref="'dynamic' + item.dynamicId"
					:imgs="item.fileName === '' ? [] : item.fileName.split(',')"
					@refresh="refreshList"
					@followChange="followChange"
					@hideTabs="isShowTabs = !isShowTabs"
					@handleHide="refreshList"
					@handleTopAndGreat="changeList"
					@moreClick="moreClick"
				></dynamic>
			</z-paging>
		</view>
		<!-- 取关动态弹窗 -->
		<confirmPopup
			:popupShow="cancelFollowPopupShow"
			title="取消关注"
			subhead="是否取消该关注"
			@popupHide="cancelFollowPopupShow = false"
			@popupConfirm="cancelFollowConfirm"
		></confirmPopup>

		<!-- 更多选择弹窗 -->
		<moreSelect
			:showOverlay="ifShowSelect"
			:record="selectData.record"
			:offsetY="selectData.offsetY"
			@hideOverlay="moreSelectHide"
			@specificFunc="selectSpecificFunc"
		></moreSelect>
		<!-- 后台收到的通知弹窗 -->
		<notice-popup :show="someThing.isShow" @close="someThing.isShow = false" @confirm="someThingConfirm"></notice-popup>
		<u-popup :show="popupState" mode="center" bgColor="transparent">
			<view class="notice">
				<view class="topImgs">
					<view class="topTitle">官方公告</view>
					<view class="topTitleFont">关于禁止炒作数字藏品的公告</view>
				</view>
				<view class="noticeView">
					<view class="noticeFont">
						亲爱的小镇居民：
						轻松小镇上线以来一直坚持合法合规运营，官方不支持也不鼓励任何形式的交易、炒作行为，未来轻松小镇也将继续坚持执行防范金融化、杜绝虚拟数字货币和撮合交易、倡导理性消费宗旨。为各位用户带来更加安全、长期的平台体验。
					</view>
					<view class="noticeButton" @tap="popupState = false"><view class="noticeViewButton">我已知晓</view></view>
				</view>
			</view>
		</u-popup>
		<!-- 蓝牙突然断开链接重新链接弹框 -->
		<!-- <example-popup ref="examplePopups" :id="propId" @cancel="onCancel" @success="onSuccess"></example-popup> -->
	</view>
</template>

<script>
import Bluetooth from '@/pages/town/common/Bluetooth.js';
import examplePopup from '@/pages/town/components/examplePopup.vue';
import { dormancyMassage } from '@/api/bluetooth.js';
import dynamic from '../community/common/dynamic.vue';
import { jump } from '../../utility/bannerJump.js';
import { communityListApi, communityBannerListApi, unreadMessageAllApi, communityKingkongListApi, communityPlateListApi, userFollowAddApi } from '../../api/index.js';
import { isShowPopup } from '../../api/user.js';
import confirmPopup from '../community/common/currencyPopup.vue';
import { ifLoginFun } from '../../utility/weChatLogin.js';
import ZPagingMixin from '@/uni_modules/z-paging/components/z-paging/js/z-paging-mixin';
import dynamicMore from '../../common/mixin/dynamic.js';
import moreSelect from '../community/common/dynamicMore.vue';
import NoticePopup from './common/noticePopup.vue';

let bluetooth = new Bluetooth();

export default {
	mixins: [ZPagingMixin, dynamicMore],
	components: {
		dynamic,
		confirmPopup,
		moreSelect,
		NoticePopup,
		examplePopup
	},
	data() {
		return {
			isShowTabs: true,
			tabsList: [],
			dataList: [],
			tabsActiveItem: {
				id: 1
			},
			bannerList: [],
			message: {
				commentNum: 0,
				followers: 0,
				likeNum: 0
			},
			kingkongList: [
				{
					image: '',
					title: '',
					jump: '',
					id: 0
				}
			],
			ifNavBarChange: false, //导航栏背景色是否变化
			tabActiveIndex: 0,
			empty: {
				emptyText: '这个板块最近没有新动态哦！先去看看其他板块动态吧～',
				emptyImgUrl: '/static/empty/index-empty.png',
				emptyImgStyle: {
					width: '215px',
					height: '154px'
				}
			},
			offsetTop: 0, // navbar的高度
			pageTop: 0, // banner+金刚图的高度
			tabsHeight: 0,
			sticky: false,
			cancelFollowPopupShow: false,
			followData: {},
			selectData: {
				record: {},
				offsetY: 0
			},
			ifShowSelect: false,
			// 后台获取的弹窗数据
			someThing: {
				isShow: false,
				title: '提示',
				content: ''
			},

			socketTasks: null,
			timerOut: null,
			timeNumber: 0,
			bluetoothData: {}, //蓝牙重新连接数据
			propId: '', //蓝牙道具id
			popupState: false
		};
	},
	onHide() {},
	computed: {},
	onLoad() {
		// this.getTabsList()
		// console.log(plus.push.getClientInfo())
		// uni.removeStorageSync('shieldList');
		this.init();
		this.handleShowPopup();
		this.getMessages();
	},
	onShow() {
		uni.$once('detailBlack', data => {
			this.getMessages();
			this.$refs.paging.reload();
		});
		setTimeout(() => {
			if (this.$store.state.userToken !== '') {
				this.onDormancyMassage();
			}
		}, 400);
	},
	mounted() {
		this.onHeight();
	},
	onPageScroll(e) {
		e.scrollTop > 200 ? uni.$u.throttle(this.setNavBarColor, 800) : (this.ifNavBarChange = false);
		if (e.scrollTop === 0) {
			this.$refs.paging.reload(true);
		}
		if (this.isShowTabs) {
			const query = uni.createSelectorQuery().in(this);
			query
				.select('#tabs')
				.boundingClientRect(data => {
					this.tabsHeight = data.height;
					Math.round(data.top) === this.offsetTop ? (this.sticky = true) : (this.sticky = false);
				})
				.exec();
		}
	},
	onReady() {
		// this.onSDHeartRate()
		this.getOffsetTop();
		// this.onGetApi();
	},
	methods: {
		toSleep() {
			uni.navigateTo({
				url: '../sleep/index'
			})
		},
		async onSDHeartRate(){
			let platform = uni.getSystemInfoSync().platform,
				xinlvjiancePlugin,
				xinlv;
			if (platform == 'android') {
				xinlvjiancePlugin = uni.requireNativePlugin('Chen-HeartRate');
			} else {
				xinlvjiancePlugin = uni.requireNativePlugin('SDHeartRate');
			}
			await xinlvjiancePlugin.addEventListener()    //添加事件监听
			xinlv = await xinlvjiancePlugin.goToVCAndStartTest()  //前往心率检测
			console.log('goToVCAndStartTest', xinlvjiancePlugin.getHeartRateResult())
		},
		onHeight() {
			const query = uni.createSelectorQuery().in(this);
			query
				.select('#textFont')
				.boundingClientRect(data => {
					console.log(1234, data);
					// this.elData = data;
					// this.$forceUpdate()
				})
				.exec();
		},
		async onGetApi() {
			try {
				let i = await this.$apiIndex.onApiIndex().communityBannerListApi();
				console.log(113, i);
			} catch (err) {
				console.log(111, err);
			}
		},
		getOffsetTop() {
			const query = uni.createSelectorQuery().in(this);
			query
				.select('#nav')
				.boundingClientRect(data => {
					this.offsetTop = data.height;
				})
				.exec();
			query
				.select('#top')
				.boundingClientRect(data => {
					this.pageTop = data.height;
				})
				.exec();
		},

		//tabs 点击
		tabsClick(item) {
			this.tabsActiveItem = item;
			if (this.sticky === true) {
				uni.pageScrollTo({
					scrollTop: this.pageTop - this.tabsHeight
				});
			}
			// 刷新整个列表。
			this.$refs.paging.reload();
		},
		tabarClick() {
			this.$refs.paging.reload(true);
		},
		//跳转搜索页
		toSearch() {
			uni.navigateTo({
				url: '../community/search'
			});
		},
		//检测用户是否有未断开的设备
		async onDormancyMassage() {
			try {
				const datas = await dormancyMassage();
				this.bluetoothData = datas.data;
				console.log('connectData', uni.getStorageSync('connectData'));
				console.log('dormancyMassage', datas);
				if (this.bluetoothData.is_show && !this.bluetoothData.is_end && JSON.stringify(uni.getStorageSync('connectData')) != '{}') {
					this.propId = this.bluetoothData.message_id;
					console.log('propId', this.propId);
					this.$refs.examplePopups.onTipsrunt(true, '检测到你有未完成艾灸', `预使用完成可获得${this.bluetoothData.max_score}元气`, {
						textOne: '确认退出',
						textTwo: '重新连接'
					});
				}
			} catch (err) {
				console.log(err);
			}
		},
		//点击左侧按钮
		async onCancel() {
			this.$refs.examplePopups.onMessageEnd(uni.getStorageSync('connectData').massage_Type, '', 'index');
		},
		//点击右侧按钮并重新连接
		onSuccess() {
			let deviceId = uni.getStorageSync('connectData').deviceId;
			bluetooth
				.openBluetoothAdapter()
				.then(res => {
					bluetooth.getBluetoothAdapterState().then(res => {
						bluetooth
							.createBLEConnection(deviceId)
							.then(res => {
								bluetooth.getBLEDeviceServices().then(service => {
									let i;
									if (uni.getSystemInfoSync().platform == 'android') {
										i = 0;
										uni.setStorageSync('servicesId', service[i].uuid);
										bluetooth.getBLEDeviceCharacteristics(2).then(rest => {
											uni.setStorageSync('servicesId', service[2].uuid); //安卓会返三个ID 需要拿第一个ID当作servicesId  第三个的ID拿取返回需要的值
											this.onResdBle();
										});
									} else {
										i = 0;
										uni.setStorageSync('serviceId', service[i].uuid);
										this.onResdBle();
									}
								});
							})
							.catch(err => {
								bluetooth.openBluetoothAdapter('蓝牙连接失败', 'none', 2000);
								setTimeout(() => {
									uni.navigateTo({
										url: `/pages/town/ready?id=${uni.getStorageSync('connectData').id}`
									});
								}, 2000);
							});
					});
				})
				.catch(err => {
					bluetooth.openBluetoothAdapter('蓝牙未打开', 'none', 2000);
				});
		},
		//返回设备
		onResdBle() {
			bluetooth.getBLEDeviceCharacteristics().then(ints => {
				bluetooth.notifyBLECharacteristicValue().then(infos => {
					this.$refs.examplePopups.onSwitch(9, 'close');
					uni.navigateTo({
						url: `/pages/town/example/manipulation?id=${uni.getStorageSync('connectData').id}`,
						animationType: 'slide-in-right',
						animationDuration: 1000
					});
				}); //开始启用notify功能
			});
		},
		//跳转消息页
		toMessage() {
			//判断是否登录
			if (!ifLoginFun()) {
				return;
			}
			uni.navigateTo({
				url: '../community/message'
			});
		},
		async init() {
			try {
				//首页banner
				const bannerRes = await communityBannerListApi();
				this.bannerList = bannerRes.data;

				const kingkongRes = await communityKingkongListApi();
				this.kingkongList = kingkongRes.data;
			} catch (e) {
				console.log(e);
				//TODO handle the exception
			}
		},
		async getMessages() {
			try {
				//判断是否有token
				if (this.$store.state.userToken !== '') {
					console.log('进入');
					//消息
					const message = await unreadMessageAllApi();
					this.message = message.data;
				}
			} catch (e) {
				console.log(e);
				//TODO handle the exception
			}
		},
		//下拉刷新,上拉加载
		async queryList(pageNo, pageSize) {
			try {
				await this.getTabsList();

				const res = await communityListApi({
					pageNum: pageNo,
					pageSize,
					plate: this.tabsActiveItem.id,
					isFollow: !this.tabsActiveItem.id ? true : false
				});
				console.log(res);
				this.$refs.paging.complete(res.data);
			} catch (e) {
				console.log(e);
				// 如果请求失败
				this.$refs.paging.complete(false); //展示错误页面
			}
		},

		async getTabsList() {
			try {
				const plateRes = await communityPlateListApi({
					pageNum: 1,
					pageSize: 10
				});
				this.tabsList = plateRes.data.map((item, index) => {
					if (item.plate === '藏品分享') {
						this.tabActiveIndex = item.id;
					}
					return {
						name: item.plate,
						...item
					};
				});

				this.tabsList.unshift({
					id: 0,
					name: '关注',
					plate: '关注'
				});
			} catch (e) {}
		},

		//更改导航栏颜色
		setNavBarColor() {
			this.ifNavBarChange = true;
		},

		//轮播点击
		swiperClick(index) {
			//跳转
			jump(this.bannerList[index]);
		},

		//跳转发布页面
		toRelease() {
			//判断是否登录
			// if (!ifLoginFun()) {
			// 	return;
			// }
			// uni.navigateTo({
			// 	url: '../community/releaseDynamic'
			// });


			// 去搜索页面
			// uni.navigateTo({
			// 	url: '/pages/ring/index'
			// });

			// uni.navigateTo({
			// 	url: '/pages/ring/search'
			// });

			// uni.navigateTo({
			// 	url: '/pages/ring/connect'
			// });

			uni.navigateTo({
				url: '/pages/ring/detail/index'
			});
		},

		//轮播下方数据点击
		kingkongClick(item) {
			jump(item);
		},

		//删除后刷新数据
		refreshList() {
			this.$refs.paging.reload();
		},

		cancelFollowConfirm() {
			this.handleFollow(this.followData);
		},

		async handleFollow(item) {
			try {
				const res = await userFollowAddApi({
					beFollowId: item.userId,
					following: !item.isFollow
				});
				let data = {
					userId: item.userId,
					isFollow: !item.isFollow
				};
				this.cancelFollowPopupShow = false;
				if (item.isFollow) {
					uni.showToast({
						title: '取关成功',
						icon: 'none'
					});
				} else {
					uni.showToast({
						title: '关注成功',
						icon: 'none'
					});
				}
				let pattern = new RegExp('[\u4E00-\u9FA5]+'),
					pattern2 = new RegExp('[A-Za-z]+'),
					pattern3 = new RegExp('[0-9]+');
				this.dataList.forEach((item, index) => {
					this.dataList[index].isFollow = data.userId === this.dataList[index].userId ? data.isFollow : this.dataList[index].isFollow;
					// if()
					console.log(item);
				});
			} catch (e) {
				//TODO handle the exception
				console.log(e);
				uni.showToast({
					title: e.message || e.data,
					icon: 'none'
				});
			}
		},
		//点击关注后修改整个数据
		followChange(data) {
			if (data.isFollow) {
				this.followData = data;
				this.cancelFollowPopupShow = true;
			} else {
				this.handleFollow(data);
			}
		},
		// 修改置顶加精
		changeList(data) {
			console.log(data);
			this.dataList.forEach((item, index) => {
				this.dataList[index][data.type] = data.dynamicId === this.dataList[index].dynamicId ? data.value : this.dataList[index][data.type];
			});
		},
		// 是否展示弹窗
		handleShowPopup() {
			if (!this.$store.state.userToken) return;
			isShowPopup()
				.then(res => {
					this.someThing.title = res.data.title;
					this.someThing.content = res.data.msg;
					this.someThing.jumpLink = res.data.jumpLink;
					this.someThing.isShow = res.data.isShow;
				})
				.catch(err => console.log(err));
		},
		someThingConfirm() {
			this.someThing.isShow = false;
			if (!this.someThing.jumpLink) return;
			if (this.someThing.jumpLink.indexOf('http') > -1) {
				const token = this.$store.state.collectionToken;
				const url = `${this.someThing.jumpLink.split('#')[0]}?token=${token}#${this.someThing.jumpLink.split('#')[1]}`;
				uni.navigateTo({
					url: `/pages/collection/otherPage?url=${url}`
				});
			} else if (this.someThing.jumpLink.indexOf('http') == -1 && this.someThing.jumpLink.indexOf('pages') > -1) {
				uni.navigateTo({
					url: this.someThing.jumpLink
				});
			}
		}
	}
};
</script>

<style lang="scss">
.notice {
	width: 85%;
	margin: auto;
	.topImgs {
		background-image: url('@/static/noticeImg.png');
		background-size: 100% 100%;
		height: 160rpx;
		background-repeat: no-repeat;
		padding: 60rpx 40rpx 0;
		.topTitle {
			font-size: 32rpx;
			color: #000000;
			margin-bottom: 10rpx;
			font-weight: 700;
		}
		.topTitleFont {
			color: #ee7b00;
			font-size: 28rpx;
			font-weight: 700;
		}
	}
	.noticeView {
		background: #fff;
		border-radius: 44rpx;
		padding: 44rpx;
		margin-top: -40rpx;
		.noticeFont {
			font-size: 26rpx;
			line-height: 44rpx;
		}
		.noticeButton {
			margin-top: 20rpx;
			.noticeViewButton {
				background: #000000;
				color: #ffffff;
				width: 100%;
				display: flex;
				justify-content: center;
				align-items: center;
				border-radius: 50rpx;
				padding: 20rpx 0;
				font-size: 13px;
			}
		}
	}
}
.box-no-sliding {
	position: fixed;
	width: 100%;
	height: 100%;
}

.swiper {
	margin-bottom: 50rpx;
}

.fade-enter-active,
.fade-leave-active {
	transition: opacity 0.5s;
}

.fade-enter,
.fade-leave-to {
	opacity: 0;
}

.publish-icon {
	position: fixed;
	right: 12px;
	bottom: 120px;
	width: 73rpx;
	height: 73rpx;
	border-radius: 50%;
	background-color: #747474;
	display: flex;
	justify-content: center;
	align-items: center;
	z-index: 99;
}

.navbar {
	position: fixed;
	top: 0;
	z-index: 999;

	.navbar-left {
		font-size: 52rpx;
		font-weight: bold;
		color: #ffffff;
	}

	.navbar-right {
		justify-content: space-between;
	}
}

.main {
	justify-content: space-between;

	.main-item {
		text-align: center;

		image {
			width: 76rpx;
			height: 76rpx;
			border-radius: $uni-border-radius-circle;
			margin-bottom: 12rpx;
		}

		view {
			color: rgba(51, 51, 51, 1);
			font-size: $uni-font-size-base;
		}
	}
}

.tabs {
	margin-top: 20rpx;
	background-color: #ffffff;
	padding-bottom: 20rpx;
	background-color: #ffffff;
	position: relative;
	z-index: 10;
}
</style>
